/* qirssi
 * Copyright (c) 2009 Paulo Matias
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * Purpose: This implements a TrayHandler class with slots to answer to
 *          trayicon events.
 */

#ifndef TRAYHANDLER_H
#define TRAYHANDLER_H

#include <QObject>
#include <QSystemTrayIcon>

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include "main.h"

class TrayHandler : public QObject {
    Q_OBJECT
public:
    TrayHandler(App *parent) :QObject(parent) {}
public slots:
    /*
     * This slot resets the icon to the "off" state.
     */
    void reset_icon() {
        App *a = dynamic_cast<App*>(parent());
        assert((a != NULL));
        a->trayicon->setIcon(*a->icon_off);
    }

    /*
     * This slot is to be plugged to the trayicon's activated signal.
     */
    void activated(QSystemTrayIcon::ActivationReason reason) {
        /* Reset the icon to the "off" state. */
        reset_icon();

        /* If the icon was clicked with the left button, open irssi. */
        if(reason == QSystemTrayIcon::Trigger) {
            /* Get the preferred terminal from the QIRSSI_TERM
             * environment variable. If it doesn't exist, use
             * "urxvt -e" as default.
             */
            const char *pref_term = getenv("QIRSSI_TERM");
            if (pref_term == NULL) {
                pref_term = "urxvt -e";
            }

            /* Call the terminal with a screen containing irssi. */
            char cmd[1024];
            snprintf(cmd, sizeof(cmd), "%s screen -RdS qirssi irssi &", pref_term);
            system(cmd);
        }
    }
};

#endif // TRAYHANDLER_H
